import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { LoginResponseData } from '@/api/user'

export const useUserStore = defineStore('user', () => {
  const token = ref<string>(localStorage.getItem('token') || '')
  const userRole = ref<string>(localStorage.getItem('userRole') || '')
  const userName = ref<string>(localStorage.getItem('userName') || '')
  const accountId = ref<string>(localStorage.getItem('accountId') || '')

  const setUserInfo = (info: LoginResponseData) => {
    token.value = info.token
    userRole.value = info.role
    userName.value = info.userName
    accountId.value = info.accountId

    // 持久化存储
    localStorage.setItem('token', info.token)
    localStorage.setItem('userRole', info.role)
    localStorage.setItem('userName', info.userName)
    localStorage.setItem('accountId', info.accountId)
  }

  const clearUserInfo = () => {
    token.value = ''
    userRole.value = ''
    userName.value = ''
    accountId.value = ''

    // 清除持久化存储
    localStorage.removeItem('token')
    localStorage.removeItem('userRole')
    localStorage.removeItem('userName')
    localStorage.removeItem('accountId')
  }

  return {
    token,
    userRole,
    userName,
    accountId,
    setUserInfo,
    clearUserInfo,
  }
})
